<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>参数列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片试图 -->
    <el-card>
      <!-- 警告区域 -->
      <el-alert :closable="false" title="注意:只允许为第三级分类设置相关参数!" type="warning" show-icon></el-alert>
      <!-- 选择商品分类区域 -->
      <el-row class="cat">
        <el-col>
          <span>请选择商品:</span>
          <!-- 级联选择框 -->
          <el-cascader
            clearable
            v-model="selectKeys"
            :options="goodsCateList"
            :props="{
              expandTrigger: 'hover',
              checkStrictly: 'true',
              value: 'cat_id',
              label: 'cat_name',
              children: 'children'
            }"
            @change="HandleChange"
          ></el-cascader>
        </el-col>
      </el-row>
      <!-- tabs标键 -->
      <el-tabs v-model="activeName" @tab-click="handleTabClick">
        <el-tab-pane label="动态参数" name="many">
          <el-button type="primary" size="mini" :disabled="!isShowBtn" @click="ShowAddDialog">添加参数</el-button>
          <!-- 动态参数表格 -->
          <el-table :data="manyDate" border stripe>
            <el-table-column type="expand">
              <template slot-scope="scope">
                <!-- //循环渲染tag标签 -->
                <el-tag
                  v-for="(item,index) in scope.row.attr_vals"
                  :key="index"
                  closable
                  @close="tagClose(index,scope.row)"
                >{{item}}</el-tag>
                <!-- 新增属性tag标签 -->
                <el-input
                  class="input-new-tag"
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                ></el-input>
                <el-button
                  v-else
                  class="button-new-tag"
                  size="small"
                  @click="showInput(scope.row)"
                >+ New Tag</el-button>
              </template>
            </el-table-column>
            <el-table-column type="index"></el-table-column>
            <el-table-column label="参数名称" prop="attr_name"></el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button
                  size="mini"
                  type="primary"
                  icon="el-icon-edit"
                  @click="ShowEditDialog(scope.row.attr_id)"
                >修改</el-button>
                <el-button
                  size="mini"
                  type="danger"
                  icon="el-icon-delete"
                  @click="deleteParamsById(scope.row.attr_id)"
                >删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
        <el-tab-pane label="静态配置" name="only">
          <el-button type="primary" size="mini" :disabled="!isShowBtn" @click="ShowAddDialog">添加属性</el-button>
          <!-- 静态属性表格 -->
          <el-table :data="onlyDate" border stripe>
            <el-table-column type="expand">
              <template slot-scope="scope">
                <!-- //循环渲染tag标签 -->
                <el-tag
                  v-for="(item,index) in scope.row.attr_vals"
                  :key="index"
                  closable
                  @close="tagClose(index,scope.row)"
                >{{item}}</el-tag>
                <!-- 新增属性tag标签 -->
                <el-input
                  class="input-new-tag"
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                ></el-input>
                <el-button
                  v-else
                  class="button-new-tag"
                  size="small"
                  @click="showInput(scope.row)"
                >+ New Tag</el-button>
              </template>
            </el-table-column>
            <el-table-column type="index"></el-table-column>
            <el-table-column label="属性名称" prop="attr_name"></el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button
                  size="mini"
                  type="primary"
                  icon="el-icon-edit"
                  @click="ShowEditDialog(scope.row.attr_id)"
                >修改</el-button>
                <el-button
                  size="mini"
                  type="danger"
                  icon="el-icon-delete"
                  @click="deleteParamsById(scope.row.attr_id)"
                >删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
    </el-card>
    <!-- 添加参数的dialog -->
    <el-dialog
      :title="'添加' + titleText"
      :visible.sync="addDialogVisible"
      width="50%"
      @close="addDialogClose"
    >
      <el-form :model="addForm" :rules="addFormrules" ref="addFormRef" label-width="100px">
        <el-form-item :label="titleText" prop="attr_name">
          <el-input v-model="addForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addParams">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 修改参数的dialog -->
    <el-dialog
      :title="'修改' + titleText"
      :visible.sync="editDialogVisible"
      width="50%"
      @close="editDialogClose"
    >
      <el-form :model="editForm" :rules="editFormrules" ref="editFormRef" label-width="100px">
        <el-form-item :label="titleText" prop="attr_name">
          <el-input v-model="editForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editParams">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
export default {
  name: "Params",
  data() {
    return {
      // 商品列表数据
      goodsCateList: [],
      // 存放级联选择器的等级
      selectKeys: [],
      // tbas标键绑定数据
      activeName: "many",
      // 动态参数的数据
      manyDate: [],
      // 静态配置的参数
      onlyDate: [],
      // 控制是否显示添加参数的dialog
      addDialogVisible: false,
      // 控制是否显示修改参数的dialog
      editDialogVisible: false,
      // // 控制tagInput是否显示
      // inputVisible: false,
      // 添加验证规则
      addFormrules: {
        attr_name: [
          { required: true, message: "请输入参数名称!", trigger: "blur" },
        ],
      },
      // 修改验证规则
      editFormrules: {
        attr_name: [
          { required: true, message: "请输入参数名称!", trigger: "blur" },
        ],
      },
      // 添加参数的数据
      addForm: {
        attr_name: "",
      },
      // 修改参数的数据
      editForm: {},
      // tagInput的数据绑定
      // inputValue: "",
    };
  },
  methods: {
    //获取商品列表数据
    async getGoodsCate() {
      const { data: res } = await this.$http.get("categories");
      if (res.meta.status == 200) {
        this.goodsCateList = res.data;
      } else {
        this.$message("获取商品数据失败!");
      }
    },
    // 级联选择框发生改变时会触发
    HandleChange() {
      this.getParamsDate();
    },
    // tabs发生点击时候触发的事件
    handleTabClick() {
      this.getParamsDate();
    },
    // 获取参数的列表数据 {
    async getParamsDate() {
      // 证明选中的不是三级分类
      if (this.selectKeys.length !== 3) {
        this.selectKeys = [];
        this.onlyDate = [];
        this.manyDate = [];
        return;
      } else {
        const { data: res } = await this.$http.get(
          `categories/${this.cateId}/attributes`,
          {
            params: { sel: this.activeName },
          }
        );
        if (res.meta.status == 200) {
          res.data.forEach((item) => {
            item.attr_vals = item.attr_vals ? item.attr_vals.split(",") : [];
            item.inputVisible = false;
            item.inputValue = "";
          });
          console.log(res.data);
          // this.$message.success("获取参数成功!");
          if (this.activeName === "many") {
            this.manyDate = res.data;
          } else {
            this.onlyDate = res.data;
          }
          // console.log(res.data);
        } else {
          this.$message.error("获取参数失败!");
        }
      }
    },
    // 显示添加dialog
    ShowAddDialog() {
      this.addDialogVisible = true;
    },
    //显示修改dialog
    async ShowEditDialog(attr_id) {
      const { data: res } = await this.$http.get(
        `categories/${this.cateId}/attributes/${attr_id}`,
        {
          params: {
            attr_sel: this.activeName,
          },
        }
      );
      if (res.meta.status == 200) {
        this.editForm = res.data;
      } else {
        this.$message.error("获取失败!");
      }
      this.editDialogVisible = true;
    },
    // 监听添加对话框的关闭事件
    addDialogClose() {
      this.$refs.addFormRef.resetFields();
    },
    // 监听修改对话框的关闭事件
    editDialogClose() {
      this.$refs.editFormRef.resetFields();
    },
    // 确定添加参数配置
    addParams() {
      this.$refs.addFormRef.validate(async (vid) => {
        if (vid) {
          const { data: res } = await this.$http.post(
            `categories/${this.cateId}/attributes`,
            {
              attr_name: this.addForm.attr_name,
              attr_sel: this.activeName,
            }
          );
          if (res.meta.status == 201) {
            this.$message.success("添加成功!");
            this.addDialogVisible = false;
            this.getParamsDate();
          } else {
            this.$message.error("添加失败!");
            console.log(res.meta.msg);
          }
        }
      });
    },
    // 确定修改参数配置
    editParams() {
      this.$refs.editFormRef.validate(async (vid) => {
        if (vid) {
          const { data: res } = await this.$http.put(
            `categories/${this.cateId}/attributes/${this.editForm.attr_id}`,
            {
              attr_name: this.editForm.attr_name,
              attr_sel: this.editForm.attr_sel,
            }
          );
          if (res.meta.status == 200) {
            this.$message.success("修改成功!");
            this.editDialogVisible = false;
            this.getParamsDate();
          } else {
            this.$message.error("修改失败!");
          }
        }
      });
    },
    // 根据id删除用户信息
    async deleteParamsById(attr_id) {
      const confirmRlust = await this.$confirm(
        "此操作将永久删除该用户, 是否继续?",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      ).catch((err) => err);
      //如果用户点了确定泽返回字符串confirm,选择了取消返回字符串cancel
      if (confirmRlust === "confirm") {
        const { data: res } = await this.$http.delete(
          `categories/${this.cateId}/attributes/${attr_id}`
        );
        if (res.meta.status == 200) {
          this.$message.success("删除分类成功!");
          this.getParamsDate();
        } else {
          this.$message.error("删除分类失败!");
          this.getParamsDate();
        }
      } else {
        this.$message.info("取消了删除!");
      }
    },
    // 保存修改后的参数
    async saveTageValus(row) {
      // 重新提交编辑后的tag标签道数据库
      const { data: res } = await this.$http.put(
        `categories/${this.cateId}/attributes/${row.attr_id}`,
        {
          attr_name: row.attr_name,
          attr_sel: row.attr_sel,
          attr_vals: row.attr_vals + "",
        }
      );
      if (res.meta.status == 200) {
        this.$message.success("修改参数成功!");
      } else {
        this.$message.error("修改参数失败!");
      }
    },
    // tagInpt按下回车和鼠标离开会触发的事件
    async handleInputConfirm(row) {
      if (row.inputValue.trim().length === 0) {
        row.inputValue = "";
        row.inputVisible = false;
      } else {
        // 输入的参数是有效参数
        row.attr_vals.push(row.inputValue.trim());
        row.inputValue = "";
        row.inputVisible = false;
        // 调用修改参数的函数
        this.saveTageValus(row);
      }
      row.inputVisible = false;
    },
    // 显示tagInput的Input标签
    showInput(row) {
      row.inputVisible = true;
      // tag问板框自动获得焦点
      // $nextTick方法作用,当元素被重新渲染后,才会执行指定代码
      this.$nextTick((_) => {
        this.$refs.saveTagInput.$refs.input.focus();
      });
    },
    // 删除动态添加的tag标签
    tagClose(index, row) {
      //删除一项tag标签
      row.attr_vals.splice(index, 1);
      // 调用修改参数的函数
      this.saveTageValus(row);
    },
  },
  created() {
    // 获取商品参数
    this.getGoodsCate();
  },
  components: {},
  computed: {
    // 通过判断级联选择框的数据长度来判断按钮是否可用
    isShowBtn() {
      if (this.selectKeys.length !== 3) {
        return false;
      } else {
        return true;
      }
    },
    // 获取三级分类的id
    cateId() {
      if (this.selectKeys.length === 3) {
        return this.selectKeys[2];
      } else {
        return null;
      }
    },
    // dialog标题
    titleText() {
      if (this.activeName === "many") {
        return "动态参数";
      } else {
        return "静态配置";
      }
    },
  },
  beforeMount() {},
  mounted() {},
  watch: {},
};
</script>
<style lang="less" scoped>
.cat {
  margin: 15px;
}
.el-tag {
  margin: 10px;
}
.input-new-tag {
  width: 120px;
}
</style>
